import type { App } from 'vue'
import { createI18n } from 'vue-i18n'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import type { I18n, I18nOptions } from 'vue-i18n'
import { setHtmlPageLang } from './helper'
// 直接导入语言文件
import zhCN from '../../locales/zh-CN'
import en from '../../locales/en'

export let i18n: ReturnType<typeof createI18n>

const createI18nOptions = async (): Promise<I18nOptions> => {
  const localeStore = useLocaleStoreWithOut()
  const locale = localeStore.getCurrentLocale
  const localeMap = localeStore.getLocaleMap

  // 确保使用 zh-CN 作为默认语言，同时处理 zh 映射
  const currentLang = locale.lang === 'zh' ? 'zh-CN' : locale.lang

  // 调试：打印加载的消息
  console.log('Loading i18n messages for lang:', currentLang)
  console.log('zh-CN messages:', zhCN)
  console.log('en messages:', en)

  setHtmlPageLang(currentLang)

  localeStore.setCurrentLocale({
    lang: currentLang
    // elLocale: elLocal
  })

  // 预加载所有语言消息
  const messages: Record<string, any> = {
    'zh-CN': zhCN,
    zh: zhCN, // 为兼容性添加 zh 映射
    en: en
  }

  return {
    legacy: false,
    locale: currentLang,
    fallbackLocale: 'zh-CN',
    messages,
    availableLocales: ['zh-CN', 'zh', 'en'], // 明确指定支持的语言
    sync: true,
    silentTranslationWarn: true,
    missingWarn: false,
    silentFallbackWarn: true,
    fallbackWarn: false,
    warnHtmlMessage: false
  }
}

export const setupI18n = async (app: App<Element>) => {
  const options = await createI18nOptions()
  i18n = createI18n(options) as I18n
  app.use(i18n)
}
